package com.kischang.blog.dao;

import com.kischang.blog.model.User;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Component
public class UserDao {

	@Resource
	private SessionFactory sessionFactory;

	public User findUserByUsername(String username) {
		Session session = sessionFactory.getCurrentSession();
		User user = (User) session
				.createQuery("FROM User as u where u.username=:username")
				.setString("username", username)
				.uniqueResult();
		return user;
	}

	public void updateLastLogin(int uid, String time) {
		Session session = sessionFactory.getCurrentSession();
		session.createQuery(
				"UPDATE FROM User as u SET u.lastLogin=:lastLogin WHERE u.id=:uid")
				.setString("lastLogin", time)
				.setInteger("uid", uid)
				.executeUpdate();
	}

	public void updateTicket(User user, String pwcookie) {
		Session session = sessionFactory.getCurrentSession();
		session.createQuery("UPDATE FROM User as u SET u.ticket=:ticket WHERE u.id=:uid")
				.setString("ticket", pwcookie)
				.setInteger("uid", user.getId())
				.executeUpdate();
	}
	
	public void updateTicketAndLastlogin(User user, String pwcookie,String lastlogin) {
		Session session = sessionFactory.getCurrentSession();
		session.createQuery("UPDATE FROM User as u SET u.ticket=:ticket,u.lastLogin=:lastLogin WHERE u.id=:uid")
				.setString("ticket", pwcookie)
				.setString("lastLogin", lastlogin)
				.setInteger("uid", user.getId())
				.executeUpdate();
	}

	public String getUserTicket(User user) {
		Session session = sessionFactory.getCurrentSession();
		return (String) session.createQuery("SELECT ticket FROM User as u where u.id=:uid")
				.setInteger("uid", user.getId())
				.uniqueResult();
	}

	public void save(User user) {
		sessionFactory.getCurrentSession().save(user);
	}

    @SuppressWarnings("unchecked")
    public List<User> getAll() {
        Session session = sessionFactory.getCurrentSession();
        return session.createQuery("FROM User")
                .list();
    }
}
